package com.adcc.loadsheet.billing.security;

import com.adcc.loadsheet.billing.configuration.SystemConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * 自定义权限校验器，本校验器只用了permission参数，如需要使用其他参数请自行处理
 * Created by zhaoml on 2020-04-01.
 */
@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {

    @Autowired
    SystemConfig systemConfig;

    @Override
    public boolean hasPermission(Authentication authentication, Object resources, Object operate) {
        try{
            UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
            BillingUserDetails user =  (BillingUserDetails)authentication.getPrincipal();
            if(user.getRoleAndPermission() != null && user.getRoleAndPermission().size() > 0 ){
                if(user.getRoleAndPermission().contains(operate.toString()))
                    return true;
            }
            return false;
        }catch (Exception ex){
            return false;
        }
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}